package com.xm.servlet.background.commodity;

import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.UUID;

/**
 * 上传视频
 * @author 康文程
 * @date 2024-1-19 下午 02:17
 */
@WebServlet("/background/add/commodity/video")
@MultipartConfig
public class AddCommodityVideoServlet extends HttpServlet {
    /**
     * 视频保存路径
     */
    private String savePath;

    @Override
    public void init() throws ServletException {
        super.init();
        // 从配置文件中读取视频保存路径
        Properties properties = new Properties();
        InputStream inputStream = getClass().getResourceAsStream("/config.properties");
        try {
            properties.load(inputStream);
            savePath = properties.getProperty("videoSavePath", "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        // 获取商品视频
        Part commodityVideoPart = req.getPart("commodityVideo");
        // 生成新的唯一文件名
        String fileName = generateUniqueFileName(commodityVideoPart.getSubmittedFileName());
        // 将商品视频保存到指定路径
        Path filePath = Paths.get(savePath + fileName);
        Files.createDirectories(filePath.getParent());
        // 确保目录存在
        commodityVideoPart.write(filePath.toString());
        // 返回响应信息
        resp.getWriter().print(fileName);
    }

    /**
     * 生成唯一的文件名，避免文件名冲突
     */
    private String generateUniqueFileName(String originalFileName) {
        String extension = "";
        int i = originalFileName.lastIndexOf('.');
        if (i > 0) {
            extension = originalFileName.substring(i);
        }
        return UUID.randomUUID() + extension;
    }
}
